<template>
  <div class="login">
    <div class="title-container">
      <h3 class="title">OJ系统 学员登录</h3>
    </div>
    <div class="login-form-container">
      <img src="../assets/极课堂logo.png" style="margin: 40px 192px 10px 192px; width: 136px; height: 33px">


      <el-form ref="loginForm2" :rules="loginFormRules" :model="loginForm" class="login-form"
               >
        <el-form-item prop="phone">
          <el-input v-model="loginForm.phone" placeholder="请输入手机号">
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input type="password" v-model="loginForm.password" placeholder="请输入密码">
          </el-input>
        </el-form-item>
        <el-row>
          <el-button class="login-button1" @click="loginSubmit()">登录</el-button>
          <el-button class="login-button1" @click="dialogVisible = true">注册</el-button>
        </el-row>
      </el-form>


      <el-dialog v-model="dialogVisible" title="用户注册" width="30%" center :closeOnClickModal="false" :showClose="false">
        <el-form :model="registerForm" :rules="registerRules" class="registerForm" ref="myForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="registerForm.password" placeholder="请输入密码" type="password"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="registerForm.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item>
            <div style="display: flex;align-items: center">
          <el-button class="login-button" @click="getCode">获取验证码</el-button>   <el-input v-model="registerForm.code"/>
            </div>
          </el-form-item>
          <el-form-item>
          <el-button class="login-button" @click="register">注册</el-button>
          <el-button class="login-button" @click="exitRegister">退出</el-button>
          </el-form-item>
<!--滑动验证块-->
        <div>
          <Vcode :show="isShow" @success="success" @close="close" @fail='fail'></Vcode>
        </div>
        </el-form>
      </el-dialog>

    </div>
  </div>
</template>
<script setup>
import {onMounted, reactive, ref,} from 'vue'
import {useStore} from 'vuex'
import {useRouter} from 'vue-router'
import {JSEncrypt} from "jsencrypt";
import API from '@/api/login'
import {ElMessage} from "element-plus";
import Vcode from "vue3-puzzle-vcode";
import store from "@/store";
let isShow=ref(false)
onMounted(() => {
  // console.log('value:', props.value)
  store.commit('user/loginOut')
})
const registerRules =reactive({
  username: [
    {required: true, message: '用户名不可为空', trigger: 'blur'},
    {max: 20, message: '长度在 20 个字符以内', trigger: 'change'}
  ],
  password: [
    {required: true, message: '密码不可为空', trigger: 'blur'},
  ],
  phone:[
    {required: true, message: '请输入正确的手机号', trigger: 'blur'},
    {validator:function (rule,value,callback){
      if(/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)===false){
        callback(new Error("手机号格式错误"))
      }else{
        callback();
      }
      },
      trigger: "blur"
    }
  ]
})

const entry = new JSEncrypt()
const success=()=>{
  isShow.value=false
  API.getPublic().then((res)=>{
    if(res.data.code==='0'){
      // 使用jsencrypt加密
      console.log(res.data.content.publicKeyStr,'key')
      entry.setPublicKey(res.data.content.publicKeyStr)
      registerSubmitForm.username =  entry.encrypt(registerForm.username)
      registerSubmitForm.password =entry.encrypt(registerForm.password)
        console.log(registerForm.phone,'phone')
      registerSubmitForm.phone=entry.encrypt(registerForm.phone)
      registerSubmitForm.random=res.data.content.random
      API.getPhoneCode(registerSubmitForm).then((res)=>{
        if(res.data.code==='0'){
          ElMessage.success('验证通过,已发送验证码')
        }
      }).catch(response=>{
        ElMessage.error(response.response.data.message)
      })
    }
  }).catch(error=>{
    console.log(error)
  })
}

const register=()=>{
  registerSubmitForm.code=entry.encrypt(registerForm.code)
  API.userRegister(registerSubmitForm).then((res)=>{
    if(res.data.code==='0'){
      ElMessage.success('注册成功')
      init()
      dialogVisible.value=false
    }
  }).catch(response=>{
    ElMessage.error(response.response.data.message)
  })
}
const close=()=>{
  isShow.value=false
}
const fail=()=>{
  ElMessage.error('验证失败')
}
const loginForm = reactive({
  username: '',
  password: '',
  code: '',
  phone: '',
  random:''
})
let registerForm=reactive({
  username:'',
  password:'',
  phone:'',
  code:'',
  random:'',
  type:'1',
})
let registerSubmitForm=reactive({})

// const store=useStore()

const dialogVisible = ref(false)
const exitRegister=()=>{
  dialogVisible.value=false
  init()
}

const myForm =ref()

// 获取验证码
const getCode= ()=>{
  myForm.value.validate((valid)=>{
    if(valid){
      isShow.value=true
    }
  })
}
const loginFormRules = reactive({
  username: [
    {required: true, message: '账户不可为空', trigger: 'blur'},
    {max: 20, message: '长度在 20 个字符以内', trigger: 'change'}
  ],
  password: [
    {required: true, message: '密码不可为空', trigger: 'blur'},
    {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'change'}
  ]
})
const router = useRouter()
const init = ()=>{
  registerForm=reactive({
    username:'',
    password:'',
    phone:'',
    random: '',
    code:''
  })
}


let param = reactive({})


const loginSubmit = () => {
  param.type = 1
  param.loginStatus = 2
    API.getPublic().then((res) => {
      if (res.data.code === '0') {
        // 使用jsencrypt加密
        const entry = new JSEncrypt()
        entry.setPublicKey(res.data.content.publicKeyStr)
        param.phone =  entry.encrypt(loginForm.phone)
        param.password =entry.encrypt(loginForm.password)
        param.random=res.data.content.random
        API.userLogin(param).then((result)=>{
          if(result.data.code==='0'){
            let token=result.data.content.token
            API.userInfo({
              size:1,
              current:1,
              phone:loginForm.phone
            },token).then(res1=>{
              console.log(res1,1111)
              if(res1.data.content.records[0].identify===4){
                localStorage.setItem('token',token)
                localStorage.setItem('loginuserphone',loginForm.phone)
                store.commit('user/logined')
                router.push( { path: '/public'})
              }
              else{
                ElMessage.error('身份错误！当前为用户端')
              }
            })
          }
        }).catch(res=>{
          // setTimeout(function (){window.location.reload(true)},1000)
          ElMessage.error(res.response.data.message)
        })
      }
    }).catch(error=>{
      console.log(error)
    })
}
</script>

<style scoped>

.login {
  position: fixed;
  height: 100%;
  width: 100%;
  background: url("../assets/bg-login.png") no-repeat center;
  background-size: 100% 100%;
  color: white;
}

.login-form-container {
  position: absolute;
  left: 60%;
  top: 28%;
  width: 520px;
  height: 400px;
  background-color: #D1FCF4;
  border-radius: 2%;
}

.login-form {
  position: absolute;
  left: 0;
  right: 0;
  width: 450px;
  padding: 0px 35px 10px 35px;
  margin: 15px auto;
}

.title-container .title {
  font-size: 50px;
  color: #eee;
  margin: 7% auto 40px auto;
  text-align: center;
  font-family: Serif;
}

.login .el-form-item {
  border: 1px solid rgba(255, 255, 255, 0.1);
  /* background: rgba(133, 129, 129, 0.1); */
  border-radius: 5px;
  /* color: #454545; */
  width: 320px;
  height: 60px;
  margin: 0px auto 10px auto;
}

.el-form-item .prep-icon-span {
  font-size: 20px;
}

.el-button {
  display: block;
  width: 320px;
  margin: 25px auto;
  background-image: linear-gradient(#81E6D4, #16AF93);
  border-radius: 10px;
  font-size: 20px;
  font-weight: bold;
}
.el-button.login-button{
  background:white;
  width: 120px;
  border: 1px solid;
  background-color: transparent;
  text-transform: uppercase;
  font-size: 15px;
  padding: 10px 20px;
  font-weight: 400;
}
.el-button.login-button1{
  background:white;
  width: 80px;
  border: 0.5px solid;
  text-transform: uppercase;
  font-size: 15px;
  padding: 10px 20px;
  font-weight: 400;
}

a {
  font-size: 13px;
  color: black;
  cursor: pointer;
  text-decoration: none;
  margin-left: 20px;
}
</style>
